<script setup lang="tsx">
import { reactive, ref, onMounted } from 'vue'
import { ElMessage, ElOption, ElSelect, ElInput } from 'element-plus'
import { Table, TableColumn } from '@/components/Table'
import { modifyApi } from '@/api/document'
import { searchSupplierCateApi } from '@/api/utils/search'
const emit = defineEmits(['close', 'get-list'])

// 获取第三方所属
const options = ref()
const getSearchSupplierCateApi = async () => {
  const res = await searchSupplierCateApi({ field: 'name,abbreviation' })
  options.value = res.data.list
}
onMounted(() => {
  getSearchSupplierCateApi()
})

const props = defineProps({
  dataList: {
    type: Array,
    required: true
  }
})
const TableSchema = reactive<TableColumn[]>([
  {
    field: 'index',
    label: '序号',
    type: 'index'
  },
  {
    field: 'goods.name',
    label: '产品名称'
  },
  {
    field: 'spec_name',
    label: '规格'
  },
  {
    field: 'imgList',
    label: '图片',
    width: '100px'
  },
  {
    field: 'orig_quantity',
    label: '采购时数量'
  },
  {
    field: 'quantity',
    label: '签收数量',
    slots: {
      default: ({ row }) => {
        return (
          <ElInput v-model={row.quantity} min={1} step-strictly onBlur={() => handleBlur(row)} />
        )
      }
    }
  },
  {
    field: 'supplier_id',
    label: '第三方所属',
    slots: {
      default: ({ row }) => {
        return (
          <ElSelect v-model={row.supplier_id} onChange={() => handleBlur(row)}>
            {options.value?.map((v) => {
              return <ElOption key={v.id} label={v.name} value={v.id} />
            })}
          </ElSelect>
        )
      }
    }
  },
  {
    field: 'purchasing_price',
    label: '单价（元）'
  },
  {
    field: 'amount',
    label: '进货总价（元）'
  }
])

const handleBlur = async (row) => {
  // 验证 row.quantity 是否为正整数
  const isPositiveInteger = /^[1-9]\d*$/.test(row.quantity)

  if (!isPositiveInteger) {
    ElMessage.error('请填写正整数')
    return
  }
  try {
    const res = await modifyApi({
      id: row.id,
      quantity: row.quantity,
      supplier_id: row.supplier_id
    })
    if (res) {
      ElMessage.success(res.msg)
      // emit('get-list')
    }
  } catch (error) {
    // 处理API调用失败的情况
    ElMessage.error('失败了')
  }
}
</script>

<template>
  <Table
    :columns="TableSchema"
    :data="props.dataList"
    :image-preview="['imgList']"
    max-height="500"
    :show-overflow-tooltip="false"
  />
</template>
